"""
HiAgent插件中心API路由扩展
插件管理相关接口
"""
from fastapi import APIRouter, HTTPException, Query, Body
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
import logging

logger = logging.getLogger(__name__)

# 动态导入HiAgent插件服务
try:
    from src.llm.hiagent_app.services.plugin_service import PluginService
    logger.info("HiAgent plugin service loaded successfully")
except Exception as e:
    logger.error(f"Failed to load HiAgent plugin service: {e}")
    PluginService = None

router = APIRouter(
    prefix="/api/v1/hiagent/plugins",
    tags=["HiAgent Plugins"],
    responses={404: {"description": "Not found"}}
)

# 初始化插件服务
plugin_service = PluginService() if PluginService else None


def check_plugin_service_available():
    """检查插件服务是否可用"""
    if not plugin_service:
        raise HTTPException(
            status_code=503,
            detail="插件服务暂时不可用，请检查配置"
        )


# ==================== 请求/响应模型 ====================

class StandardResponse(BaseModel):
    """标准响应格式"""
    success: bool
    message: Optional[str] = None
    data: Optional[dict] = None


class PluginConfigRequest(BaseModel):
    """插件配置请求"""
    config: Dict[str, Any] = Field(..., description="插件配置信息")


# ==================== 插件中心API ====================

@router.get("/categories", summary="获取插件分类列表")
async def list_plugin_categories(
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取可用的插件分类"""
    check_plugin_service_available()
    try:
        categories = plugin_service.list_available_plugin_categories(workspace_id)
        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "categories": [cat.__dict__ for cat in categories],
                "total": len(categories)
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件分类失败: {str(e)}")


@router.get("", summary="获取插件列表")
async def list_plugins(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[str] = Query(None, description="分类ID"),
    keyword: Optional[str] = Query(None, description="关键词搜索"),
    plugin_type: Optional[str] = Query(None, description="插件类型"),
    is_released: Optional[bool] = Query(None, description="是否已上架"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取插件列表

    支持的筛选条件：
    - category_id: 按分类ID筛选
    - keyword: 关键词搜索（插件名称或描述）
    - plugin_type: 插件类型
    - is_released: 是否已上架
    """
    check_plugin_service_available()
    try:
        plugins, total = plugin_service.list_plugins(
            workspace_id=workspace_id,
            page=page,
            page_size=page_size,
            category_id=category_id,
            keyword=keyword,
            plugin_type=plugin_type,
            is_released=is_released
        )

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [plugin.__dict__ for plugin in plugins],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件列表失败: {str(e)}")


@router.get("/released", summary="获取已上架插件列表")
async def list_released_plugins(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[str] = Query(None, description="分类ID"),
    keyword: Optional[str] = Query(None, description="关键词搜索"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取已上架的插件列表"""
    check_plugin_service_available()
    try:
        plugins, total = plugin_service.list_released_plugins(
            workspace_id=workspace_id,
            page=page,
            page_size=page_size,
            category_id=category_id,
            keyword=keyword
        )

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [plugin.__dict__ for plugin in plugins],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取已上架插件列表失败: {str(e)}")


@router.get("/{plugin_id}", summary="获取插件详情")
async def get_plugin_detail(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取插件的详细信息"""
    check_plugin_service_available()
    try:
        plugin = plugin_service.get_plugin_detail(plugin_id, workspace_id)
        if not plugin:
            raise HTTPException(status_code=404, detail="插件不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"plugin": plugin.__dict__}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件详情失败: {str(e)}")


@router.get("/released/{plugin_id}", summary="获取已上架插件详情")
async def get_released_plugin_detail(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取已上架插件的详细信息"""
    check_plugin_service_available()
    try:
        plugin = plugin_service.get_released_plugin_detail(plugin_id, workspace_id)
        if not plugin:
            raise HTTPException(status_code=404, detail="插件不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"plugin": plugin.__dict__}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取已上架插件详情失败: {str(e)}")


# ==================== 插件收藏管理API ====================

@router.post("/{plugin_id}/favorite", summary="收藏插件")
async def favorite_plugin(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """将插件添加到收藏"""
    check_plugin_service_available()
    try:
        success = plugin_service.favorite_plugin(plugin_id, workspace_id)
        return StandardResponse(
            success=success,
            message="收藏成功" if success else "收藏失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"收藏插件失败: {str(e)}")


@router.delete("/{plugin_id}/favorite", summary="取消收藏插件")
async def unfavorite_plugin(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """从收藏中移除插件"""
    check_plugin_service_available()
    try:
        success = plugin_service.unfavorite_plugin(plugin_id, workspace_id)
        return StandardResponse(
            success=success,
            message="取消收藏成功" if success else "取消收藏失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"取消收藏失败: {str(e)}")


# ==================== 插件配置管理API ====================

@router.post("/{plugin_id}/config", summary="保存插件配置")
async def save_plugin_config(
    plugin_id: str,
    request: PluginConfigRequest,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    保存插件配置（授权）

    将插件授权配置保存到系统，使插件可用
    """
    check_plugin_service_available()
    try:
        success = plugin_service.save_plugin_config(
            plugin_id=plugin_id,
            config=request.config,
            workspace_id=workspace_id
        )
        return StandardResponse(
            success=success,
            message="配置保存成功" if success else "配置保存失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"保存插件配置失败: {str(e)}")


@router.delete("/{plugin_id}/config", summary="移除插件配置")
async def remove_plugin_config(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    移除插件配置（取消授权）

    移除插件的授权配置，使插件不可用
    """
    check_plugin_service_available()
    try:
        success = plugin_service.remove_plugin_config(plugin_id, workspace_id)
        return StandardResponse(
            success=success,
            message="配置移除成功" if success else "配置移除失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"移除插件配置失败: {str(e)}")


@router.get("/{plugin_id}/config", summary="获取插件配置")
async def get_plugin_config(
    plugin_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取插件的配置信息"""
    check_plugin_service_available()
    try:
        config = plugin_service.get_plugin_config(plugin_id, workspace_id)
        if config is None:
            raise HTTPException(status_code=404, detail="插件配置不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"config": config}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件配置失败: {str(e)}")
